package com.boot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.boot.entity.dto.UpdatePasswordDto;
import com.boot.entity.dto.UserDto;
import com.boot.mapper.RoleMapper;
import com.boot.pojo.Result;
import com.boot.service.IMenuService;
import com.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RequestMapping;

import com.boot.entity.User;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shuchong
 * @since 2022-07-03
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IMenuService menuService;
    //登录接口
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto){
        if(Objects.isNull(userDto)){
            return new Result().fail("传入的数据为空");
        }
        UserDto userDto1 = userService.login(userDto);
        return new Result().success("登录成功").add("userDto",userDto1);
    }

    //新增或者更新
    @PostMapping("/saveOrUpdate")
    public Result save(@RequestBody User user){
        System.out.println(user);
        boolean flag;
        if(Objects.isNull(user.getId())){
            flag = userService.saveOrUpdate(user);
            if(flag){
                return new Result().success("保存成功");
            }else{
                return new Result().fail("保存失败");
            }
        }else{
            flag = userService.saveOrUpdate(user);
            if(flag){
                return new Result().success("修改成功").add("avatar",user.getAvatar());
            }else{
                return new Result().fail("修改失败");
            }
        }
    }
    //删除单个
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = userService.removeById(id);
        if(flag){
            return new Result().success("执行成功");
        }else{
            return new Result().fail("执行失败");
        }
    }
    //批量删除
    @PostMapping("/dels")
    public Result delete(@RequestBody List<Integer> ids){
        boolean flag = userService.removeByIds(ids);
        if(flag){
            return new Result().success("执行成功");
        }else{
            return new Result().fail("执行失败");
        }
    }
    //修改
    @PostMapping("/update")
    public boolean update(@RequestBody User user){
        return userService.update(user,null);
    }
    //查找全部
    @GetMapping("/findAll")
    public Result findAll(){
        List<User> list = userService.list();
        return new Result().add("list",list);
    }
    //单个查找
    @GetMapping("/findOne")
    public User findOne(@PathVariable Integer id){
        return userService.getById(id);
    }
    //分页
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String nickname,
                               @RequestParam(defaultValue = "") String address){
        IPage<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(!"".equals(username)){
            queryWrapper.like("username",username);
        }
        if(!"".equals(nickname)){
            queryWrapper.like("nickname",nickname);
        }
        if(!"".equals(address)){
            queryWrapper.like("address",address);
        }
        IPage<User> page1 = userService.page(page,queryWrapper);
        return new Result().add("page",page1);
    }
    //导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        List<User> list = userService.list();
//        通过工具类创建writer 写出到磁盘路径
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username","用户名");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("nickname","昵称");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("phone","电话");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("createTime","创建时间");
        writer.addHeaderAlias("avatar","头像");

        //一次性写出list内的对象到excel,使用默认样式，强制输出标题
        writer.write(list,true);
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
//        List<User> list = reader.readAll(User.class); 方式一
//        方式2忽略表头的中文，直接读取表的内容
        List<List<Object>> read = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        read.forEach(row -> {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAvatar(row.get(6).toString());
            users.add(user);
        });
        boolean b = userService.saveBatch(users);
        if(b){
            return new Result().success("导入成功！");
        }else{
            return new Result().fail("导入失败！");
        }
    }
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        userService.register(user);
        return new Result().success("注册成功");
    }
    //修改账号密码
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordDto updatePasswordDto){
        userService.updatePassword(updatePasswordDto);
        return new Result().success("密码修改完成,请重新登录");
    }

    @GetMapping("/getData/{username}")
    public Result getData(@PathVariable("username")String username){
        User user = userService.getData(username);
        return new Result().success("数据获取成功").add("user",user);
    }
    //修改个人信息
    @PostMapping("/updatePersonData")
    public Result updatePersonData(@RequestBody User user){
        Result userDto = userService.updatePersonData(user);
        return new Result().success("个人信息修改完成,请重新登录").add("data",userDto);
    }
}
